package cn.wangqi.personal.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by admin on 2017/5/22.
 */
public class StringUtil {
    private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
    public static final ObjectMapper JSON_MAPPER_NOTNULL = new ObjectMapper();
    private static final Logger logger = Logger.getLogger(StringUtil.class);
    private static final Pattern charsetPattern = Pattern.compile("(?i)\\bcharset=\\s*\"?([^\\s;\"]*)");
    private static String userAgent = "jiecai.com";

    public StringUtil() {
    }

    public static String md5Str(InputStream ins) throws NoSuchAlgorithmException, IOException {
        return bytesToHex(md5(ins));
    }

    public static String md5Str(byte[] data) throws NoSuchAlgorithmException {
        return bytesToHex(md5(data));
    }

    public static byte[] md5(InputStream ins) throws NoSuchAlgorithmException, IOException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] buf = new byte[16384];

        while(true) {
            int readLen = ins.read(buf);
            if(readLen == -1) {
                return md5.digest();
            }

            md5.update(buf, 0, readLen);
        }
    }

    public static byte[] md5(byte[] data) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(data);
        return md5.digest();
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);

        for(int i = 0; i < bytes.length; ++i) {
            sb.append(convertDigit(bytes[i] >> 4));
            sb.append(convertDigit(bytes[i] & 15));
        }

        return sb.toString();
    }

    private static char convertDigit(int value) {
        value &= 15;
        return value >= 10?(char)(value - 10 + 97):(char)(value + 48);
    }

    public static String encodeUrl(String content, String encoding) throws UnsupportedEncodingException {
        String v = URLEncoder.encode(content, encoding);
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < v.length(); ++i) {
            char ch = v.charAt(i);
            switch(ch) {
                case '+':
                    sb.append("%20");
                    break;
                default:
                    sb.append(ch);
            }
        }

        return sb.toString();
    }

    public static long getLongValue(String s, long defaultValue) {
        if(s == null) {
            return defaultValue;
        } else {
            try {
                return Long.parseLong(s);
            } catch (Exception var4) {
                return defaultValue;
            }
        }
    }

    public static float getFloatValue(String s, float defaultValue) {
        if(s == null) {
            return defaultValue;
        } else {
            try {
                return Float.parseFloat(s);
            } catch (Exception var3) {
                return defaultValue;
            }
        }
    }

    public static short getShortValue(String s, short defaultValue) {
        if(s == null) {
            return defaultValue;
        } else {
            try {
                return Short.parseShort(s);
            } catch (Exception var3) {
                return defaultValue;
            }
        }
    }

    public static double getDoubleValue(String s, double defaultValue) {
        if(s == null) {
            return defaultValue;
        } else {
            try {
                return Double.parseDouble(s);
            } catch (Exception var4) {
                return defaultValue;
            }
        }
    }

    public static int getIntValue(String s, int defaultValue) {
        if(s != null && s.length() != 0) {
            try {
                return Integer.parseInt(s);
            } catch (Exception var3) {
                return defaultValue;
            }
        } else {
            return defaultValue;
        }
    }

    public static boolean getBooleanValue(String s, boolean defaultValue) {
        if(s == null) {
            return defaultValue;
        } else {
            try {
                return Boolean.parseBoolean(s);
            } catch (Exception var3) {
                return defaultValue;
            }
        }
    }

    public static int getPageCount(int total, int pageSize) {
        return total % pageSize == 0?total / pageSize:total / pageSize + 1;
    }

    static String getCharsetFromContentType(String contentType) {
        if(contentType == null) {
            return null;
        } else {
            Matcher m = charsetPattern.matcher(contentType);
            return m.find()?m.group(1).trim().toUpperCase():null;
        }
    }

    public static boolean isEmpty(Object str) {
        return str == null || "".equals(str);
    }

    public static boolean isNotEmpty(Object str) {
        return !isEmpty(str);
    }

    public static boolean isBlank(String str) {
        int strLen;
        if(str != null && (strLen = str.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if(!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    public static boolean isNotBlank(String str) {
        return !StringUtil.isBlank(str);
    }

    public static String getTraceString(String app, String channel, String version, String active) {
        return app + "_" + channel + "_" + version + "_" + active;
    }

    public static String hideString(String src, int starNum, int start, int end) {
        if(isEmpty(src)) {
            return src;
        } else if(starNum >= 0 && start >= 0 && start < src.length() && end >= start && end <= src.length()) {
            StringBuilder stars = new StringBuilder();

            for(int i = 0; i < starNum; ++i) {
                stars.append("*");
            }

            return src.substring(0, start + 1) + stars.toString() + src.substring(end);
        } else {
            throw new IllegalArgumentException("Invalid paramter.");
        }
    }

    public static <T> T json2Object(String content, Class<T> type) {
        try {
            return JSON_MAPPER_NOTNULL.readValue(content, type);
        } catch (IOException var3) {
            throw new IllegalArgumentException("Transforming锛坖son2Object锛� failed: " + var3.getMessage(), var3);
        }
    }

    public static <T> T json2Object(String content, TypeReference type) {
        try {
            return JSON_MAPPER_NOTNULL.readValue(content, type);
        } catch (IOException var3) {
            throw new IllegalArgumentException("Transforming锛坖son2Object锛� failed: " + var3.getMessage(), var3);
        }
    }

    public static String toJSONString(Object obj) {
        try {
            return JSON_MAPPER_NOTNULL.writeValueAsString(obj);
        } catch (Exception var2) {
            throw new IllegalArgumentException("Transforming锛坱oJSONString锛� failed: " + var2.getMessage(), var2);
        }
    }

    public static <T> List<T> stringToList(String src, String split, Class<T> clazz) {
        List<T> list = new ArrayList();
        if(isEmpty(src)) {
            return null;
        } else {
            String[] srcArr = src.split(split);
            String[] var5 = srcArr;
            int var6 = srcArr.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                String s = var5[var7];
                if(!isEmpty(s)) {
                    if("java.lang.Integer".equals(clazz.getName())) {
                        list.add((T) Integer.valueOf(s));
                    } else if("java.lang.Long".equals(clazz.getName())) {
                        list.add((T) Long.valueOf(s));
                    } else if("java.lang.Double".equals(clazz.getName())) {
                        list.add((T) Double.valueOf(s));
                    } else {
                        list.add((T) s);
                    }
                }
            }

            return list;
        }
    }

    public static String joinArray(String[] src, String split) {
        if(src != null && src.length != 0) {
            StringBuilder srcString = new StringBuilder();
            int index = 0;
            String[] var4 = src;
            int var5 = src.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                String s = var4[var6];
                if(index > 0) {
                    srcString.append(split);
                }

                srcString.append(s);
                ++index;
            }

            return srcString.toString();
        } else {
            return "";
        }
    }

    public static <T> String joinList(List<T> list, String split) {
        if(list != null && list.size() != 0) {
            StringBuilder sb = new StringBuilder();
            int i = 0;

            for(Iterator var4 = list.iterator(); var4.hasNext(); ++i) {
                T t = (T) var4.next();
                if(i != 0) {
                    sb.append(split);
                }

                sb.append(t);
            }

            return sb.toString();
        } else {
            return "";
        }
    }

    static {
        JSON_MAPPER_NOTNULL.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        JSON_MAPPER_NOTNULL.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        JSON_MAPPER_NOTNULL.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        JSON_MAPPER_NOTNULL.setLocale(Locale.getDefault());
    }
}
